package com.csii.sys.config;

import cn.hutool.core.util.StrUtil;
import com.csii.core.system.vo.LoginUser;
import com.csii.user.entity.SysUser;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置上下文
 *
 * @author HYP
 */
public class AppUserContext
{
    static ThreadLocal<Map<String,Object>> threadLocal=new ThreadLocal<>();
    /**
     * 租户id字段
     */
    public static final String TENANT_ID = "tenant_id";
    /**
     * 租户id字段
     */
    public static final String USER= "user_info";



    /**
     * 租户id默认值
     */
    public static final String tenantIDValue = "0";
    public static void setTenantId(String tenantId){
        putVal(AppUserContext.TENANT_ID, tenantId);
    }
    public static void setUser(LoginUser user){
        putVal(AppUserContext.USER, user);
        putVal(AppUserContext.TENANT_ID,user.getRelTenantIds());
    }
    public static String getTenantId()
    {
        return threadLocal.get()==null|| StrUtil.isEmpty((String)threadLocal.get().get(TENANT_ID)) ? tenantIDValue : threadLocal.get().get(TENANT_ID).toString();
    }

    public static void putVal(String key,Object val){
        if(threadLocal.get()==null)
            threadLocal.set(new HashMap<>());
        threadLocal.get().put(key,val);
    }
    public static SysUser getUser(){
        return threadLocal.get()==null?null:(SysUser)threadLocal.get().get(USER);
    }
    public static void clean(){
        threadLocal.remove();
    }

}
